package models

import (
	"time"

	"lottery/libs/mymgo"
	"lottery/utils"

	"github.com/astaxie/beego/logs"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

const (
	GAME_COL_STR = "game"
)

// 赛事
type Game struct {
	Id             int64  `json:"id" bson:"_id"`
	PlatformId     int    `json:"platformId" bson:"platformId"`         // 站点ID
	PlatformGameId string `json:"platformGameId" bson:"platformGameId"` // 站点比赛ID
	LeagueGameId   string `json:"leagueGameId" bson:"leagueGameId"`     // 站点联赛ID
	LeagueGameName string `json:"leagueGameName" bson:"leagueGameName"` // 站点联赛名称
	HName          string `json:"hname" bson:"hname"`                   // 主队
	AName          string `json:"aname" bson:"aname"`                   // 客队
	PlayTime       string `json:"playTime" bson:"playTime"`             // 比赛时间

	StartTime int64 `json:"startTime" bson:"startTime"` // 比赛时间 时间戳 毫秒

	Status      int   `json:"status" bson:"status"`   // 状态信息 1 未开始 2 比赛中 3 结束
	UserId      int64 `json:"userId" bson:"userId"`   //userId 是否不需要？
	IsAtten     bool  `json:"isAtten" bson:"isAtten"` //是否已关注
	IsDeleted   bool  `json:"isDeleted" bson:"isDeleted"`
	CreateTime  int64 `json:"createTime" bson:"createTime"`
	UpdateTime  int64 `json:"updateTime" bson:"updateTime"`
	DeletedTime int64 `json:"deletedTime" bson:"deletedTime"`
}

func FindGameBySite(platformId int, platformGameId string) (game *Game, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	game = new(Game)
	err = sess.WithC(GAME_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{
			"platformId":     platformId,
			"platformGameId": platformGameId,
		}).Select(bson.M{"_id": 1}).One(game)
	})
	return
}

func UpsertGame(game *Game) (err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}

	oldGame := new(Game)
	err = sess.WithC(GAME_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{
			"platformId":     game.PlatformId,
			"platformGameId": game.PlatformGameId,
		}).Select(bson.M{"_id": 1, "createTime": 1}).One(oldGame)
	})

	if err != nil {
		if err == mgo.ErrNotFound {
			game.Id = int64(sess.AutoIncId(GAME_COL_STR))
			game.CreateTime = time.Now().UnixNano() / int64(time.Millisecond)
			return sess.Insert(GAME_COL_STR, game)
		} else {
			return err
		}
	} else {
		game.Id = oldGame.Id
		return nil
		game.Id = oldGame.Id
		game.UpdateTime = time.Now().UnixNano() / int64(time.Millisecond)
		return sess.UpdateId(GAME_COL_STR, oldGame.Id, bson.M{"$set": bson.M{
			"UpdateTime": utils.CurrentMills(),
		}})
	}
	return
}

func GetGameList(userId int64, platformId int) (games []*Game, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	games = make([]*Game, 0, 50)
	times := time.Now().UnixNano()/int64(time.Millisecond) - 100*60*1000
	logs.Debug("times", times, platformId)
	if platformId == 0 {
		err = sess.WithC(GAME_COL_STR, func(col *mgo.Collection) error {
			return col.Find(bson.M{"isDeleted": false, "startTime": bson.M{"$gt": times}}).Sort("-startTime").All(&games)
		})

	} else {
		err = sess.WithC(GAME_COL_STR, func(col *mgo.Collection) error {
			return col.Find(bson.M{"isDeleted": false, "platformId": platformId, "startTime": bson.M{"$gt": times}}).Sort("-startTime").All(&games)
		})
	}
	policys, _, err := GetPolicyList(userId, 0, 100)
	for _, game := range games {
		for _, policy := range policys {
			if policy.Platform1GameId == game.Id || policy.Platform2GameId == game.Id {
				game.IsAtten = true
				break
			}
		}
	}
	return
}
func ExistsPlatformIdAndPlatformGameId(platformId int, platformgameId int64) (exist bool) {

	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	return sess.Exist(GAME_COL_STR, bson.M{"platformId": platformId, "_id": platformgameId})
}
func GetGameInfo(platformId int, platformGameId int64) (game *Game, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	game = new(Game)

	err = sess.One(GAME_COL_STR, bson.M{"platformId": platformId, "_id": platformGameId}, game)
	return
}

func GetSilceGameInfo(gameSilce []int64) (games []*Game, err error) {
	sess, err := mymgo.OpenBase()
	if err != nil {
		return
	}
	games = make([]*Game, 0, 40)

	err = sess.WithC(GAME_COL_STR, func(col *mgo.Collection) error {
		return col.Find(bson.M{"isDeleted": false, "_id": bson.M{"$in": gameSilce}}).All(&games)
	})
	return
}
